package cn.itcast.server.service.handler;

import cn.itcast.message.GroupCreateRequestMessage;
import cn.itcast.message.GroupCreateResponseMessage;
import cn.itcast.server.session.Group;
import cn.itcast.server.session.GroupSessionFactory;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import lombok.extern.slf4j.Slf4j;

import java.util.List;
import java.util.Set;

@ChannelHandler.Sharable
@Slf4j
public class GroupCreateRequestMessageHandler extends SimpleChannelInboundHandler<GroupCreateRequestMessage> {
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, GroupCreateRequestMessage msg) throws Exception {
        String groupName = msg.getGroupName();
        Set<String> members = msg.getMembers();
        Group group = GroupSessionFactory.getGroupSession().createGroup(groupName, members);
        if(group == null){
            //已创建
            Channel ownerChannel = ctx.channel();
//            log.warn("==========> {}", ownerChannel);

            //给群员发提示信息
            List<Channel> membersChannel = GroupSessionFactory.getGroupSession().getMembersChannel(groupName);
            for (Channel channel : membersChannel) {
                if (ownerChannel == channel) {
//                    log.warn("==========> {}", channel);
                    ownerChannel.writeAndFlush(new GroupCreateResponseMessage(true,
                                                                        "群聊 "+ groupName +" 创建成功！"));
                }
                channel.writeAndFlush(new GroupCreateResponseMessage(true,
                                    "您已被拉入群聊: " + groupName + "! 快来和大家打个招呼吧！"));
            }
        }else {
            ctx.channel().writeAndFlush(new GroupCreateResponseMessage(false, "群聊已存在！"));
        }
    }
}
